package com.esd.crm.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.esd.crm.Constants;
import com.esd.crm.entity.AreaCode;
import com.esd.crm.entity.Filegags;
import com.esd.crm.entity.Project;
import com.esd.crm.service.AreaCodeService;
import com.esd.crm.service.FilegagsService;
import com.esd.crm.service.ProjectService;
import com.esd.vo.PageUtil;
import com.esd.vo.ReturnResult;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/project")
public class ProjectController {
	
	private Logger logger = Logger.getLogger(ProjectController.class);
	@Value(value = "${fileNameSpliter}")
	private String fileNameSpliter;// 新旧文件名分隔符
	@Autowired
	private ProjectService projectService;
	@Autowired
	private FilegagsService filegagsService;
	@Autowired
	private AreaCodeService areaCodeService;

	/**
	 * 跳转项目查询页
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView projectList() {
		return new ModelAndView("project/project-list");
	}
	
	/**
	 * 项目查询
	 * @param param
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ReturnResult getProjectFindAll(Project param,PageUtil page) {
		PageInfo<Project> pageInfo = projectService.findProjectByPage(param, page);
		return ReturnResult.storeData(pageInfo);
	}
	
	/**
	 * 通过id删除项目
	 * @param param
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/delete",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> delete(String id,PageUtil page,HttpSession session) {
		boolean b = projectService.deleteById(id);
		if(!b) {
			return ReturnResult.fail();
		}
		filegagsService.deleteByBusinessId(id);
		
		return ReturnResult.success();
		
	}
	
	/**
	 * 批量删除
	 * @param idArray
	 * @param reuqest
	 * @return
	 */
	@RequestMapping(value="/deleteBatch", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> deleteBatch(@RequestParam("idArray")String [] idArray,HttpServletRequest reuqest,HttpSession session){
		if(idArray == null || idArray.length ==0) {
			return ReturnResult.fail("请选择要删除的项.");
		}
		int idArrayLength = idArray.length;
		
		boolean b = projectService.deleteBatch(idArray);
		if(!b) {
			return ReturnResult.fail();
		}
		for (int i = 0; i < idArrayLength; i++) {
			System.out.println("idArray[i]===>"+idArray[i]);
			filegagsService.deleteByBusinessId(idArray[i]);
		}
		return ReturnResult.success();
	}
	
	/**
	 * 跳转新增项目页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView add_get(HttpServletRequest request) {
		ReturnResult entity = ReturnResult.success();
		//1. 获取省列表
		List<AreaCode> provinceList = areaCodeService.getSubAreaAddress("");
		entity.put("provinceList", provinceList);
		entity.put(Constants.HTML_PAGE_TYPE, Constants.HTML_PAGE_TYPE_NEW);
		return new ModelAndView("project/project-html", entity);
	}
	
	/**
	 * 新增项目
	 * @param project
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> add_post(Project project,HttpServletRequest request,HttpSession session) {
		
		
		boolean b = projectService.insertSelective(project);
		if(!b) {
			return ReturnResult.fail();
		}
		return ReturnResult.success();
	}
	
	/**
	 * 修改跳转
	 * @param id
	 * @param editable
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}/{editable}", method = RequestMethod.GET)
	public ModelAndView edit_get(@PathVariable(value = "id") String id, @PathVariable(value = "editable") int editable,
			HttpServletRequest request) {
		ReturnResult entity = ReturnResult.success();
		System.out.println("editid=====>"+id);
		Project project = projectService.findOneProject(id);
		entity.put("project", project);
		areaCodeService.paraseAreaCode(project.getProvince(), project.getCity(), project.getDistrict(), entity);
		entity.put(Constants.HTML_PAGE_TYPE, Constants.HTML_PAGE_TYPE_EDIT);
		return new ModelAndView("project/project-html", entity);
	}
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> edit_post(Project project,HttpServletRequest request,HttpSession session) {
		
		String id = project.getId();
		System.out.println("id=====>"+id);
		boolean b = projectService.updateByPrimaryKeySelective(project); 
		if(!b) {
			return ReturnResult.fail();
		}
		return ReturnResult.success();
	}
	
	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
}
